﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;
using LiveShopvnext.Commods;
using LiveShopvnext.CommodityTypes;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using LiveShopvnext.CommodTool;
using LiveShopvnext.CommodOrders;
using Volo.Abp.Threading;
using Microsoft.Extensions.Caching.Distributed;
using LiveShopvnext.ExpressApi;
using LiveShopvnext.aSku;

namespace LiveShopvnext.CommoditySpecificas
{
    public class FreeActionAppService : ApplicationService, IFreeActionAppService
    {
        public IDistributedCache Cache { get; set; }
        private readonly IRepository<FreeActions, Guid> _repository;
        private readonly IRepository<CommodInfo, Guid> _repository0;
        private readonly IRepository<CommodityType, Guid> _repository1;
        private readonly IRepository<CommodSpecifica, Guid> _repository2;
        private readonly IRepository<CommodOrder, Guid> _repository3;
        private readonly IRepository<UserOrder, Guid> _repository4;
        private readonly IRepository<SpecificaPars, Guid> _repository5;
        public FreeActionAppService(IRepository<FreeActions, Guid> repository,
            IRepository<CommodInfo, Guid> repository0,
            IRepository<CommodityType, Guid> repository1,
            IRepository<CommodSpecifica, Guid> repository2,
           IRepository<CommodOrder, Guid> repository3,
            IRepository<UserOrder, Guid> repository4,
            IRepository<SpecificaPars, Guid> repository5
            )

        {
            _repository = repository;
            _repository0 = repository0;
            _repository1 = repository1;
            _repository2 = repository2;
            _repository3 = repository3;
            _repository4 = repository4;
            _repository5 = repository5;
        }



        
        public List<CommodInfoDTO> GetAll(string input)
        {
           var result= _repository0.ToList();
           
            return ObjectMapper.Map<List<CommodInfo>, List<CommodInfoDTO>>(result);
        }

        [HttpPost]
        public string Upload([FromForm] IFormFile file)
        {
            string rootdir = AppContext.BaseDirectory.Split(@"\bin\")[0];
            var path = rootdir + @"\CommodImage\" + file.FileName;
            using (System.IO.FileStream fs = System.IO.File.Create(path))
            {
                file.CopyTo(fs);
                fs.Flush();//清空文件流
            }
            
            string m =  "http://localhost:100/" + file.FileName;
            return m;//将新文件文件名回传给前端
        }

        public FreeActionDTO UserLogin(CreateUpdateFreeActionDto input)
        {
            var res = _repository.Where(s => s.Password == input.Password && s.UserName == input.UserName).ToList();
            if(res.Count()>0)
            {
                return  ObjectMapper.Map<FreeActions, FreeActionDTO>(res[0]);
            }
            else
            {
                return new FreeActionDTO { User_name = "用户名或密码错误" };
            }
        }



        public async Task<FreeActionDTO> UserPost(CreateUpdateFreeActionDto input)
        {
            input.token = true;
            var res = await _repository.InsertAsync(ObjectMapper.Map<CreateUpdateFreeActionDto, FreeActions>(input));

            return ObjectMapper.Map<FreeActions, FreeActionDTO>(res);

        }
      public static Guid  ml;


private static readonly object lockobj=new object();
        public int OrderAdd(AddDataOrder input0)
        {
            
            lock (lockobj)
            {
     try
            {
                    for (int i = 0; i < input0.input2.Count(); i++)
                    {
                    var slp = input0.input2[i].goodsku.Split(",");
                    string sk = "";
                    for (int n = 0; n < slp.Length; n++)
                    {
                        if(sk=="")
                        {
                            sk += slp[n];
                        }else
                        {
                            sk += ";" + slp[n];
                        }
                        
                    }
                    

                     Guid c=   _repository5
                            .Where(s => s.CommodId == input0.input2[i]
                            .Id&&s.SpName==sk)
                            .ToList()[0].Id;
                        
                        var dic = AsyncHelper.RunSync(() => { return _repository5.GetAsync(c); });
                            if (dic.Proid - input0.input2[i].Num < 0)
                        {
                            return 0;
                        }
                        else
                        {
                            dic.Proid = dic.Proid - input0.input2[i].Num;
                        }
                    }
                    //for (int i = 0; i < input0.input2.Count(); i++)
                    //{

                    //    Guid g = new Guid(input0.input2[i].Id);
                    //    var dic = AsyncHelper.RunSync(() => { return _repository0.GetAsync(g); });

                    //    if (dic.CommodityStock - input0.input2[i].Num < 0)
                    //    {
                    //        return 0;
                    //    }
                    //    else
                    //    {
                    //        dic.CommodityStock = dic.CommodityStock - input0.input2[i].Num;
                    //    }
                    //}

              }
            catch (Exception eN)
            {
                    return 0;
            }
                Guid strguid = Guid.NewGuid();
                var o = _repository3.ToList();
                input0.input.OrderInfoWaybillNum = strguid.ToString();
                var dic0 = AsyncHelper.RunSync(() => { return _repository3.InsertAsync(input0.input); });
                for (int i = 0; i < input0.input2.Count(); i++)
                {
                    var dic1 = AsyncHelper.RunSync(() => { return _repository4.InsertAsync(new UserOrder { GoodId = input0.input2[i].Id, OrderId = input0.input.OrderInfoWaybillNum, Num = input0.input2[i].Num, Price = input0.input2[i].Price, smallImage = input0.input2[i].smallImage, goodsku= input0.input2[i].goodsku } ); });
                }
                var k = _repository3.ToList();
                //_repository0.GetAsync();
                ml = strguid;
                return 1;
            }


        }



        public List<OrderShowData> OrderShow(int cid)
        {
            var s = (from a in _repository3
                    join b in _repository4 on a.OrderInfoWaybillNum equals b.OrderId
                     join c in _repository0 on b.GoodId equals c.Id.ToString()
                     select new OrderShowData
                     {
                          Id=a.Id.ToString(),
                           MemberId=a.MemberId,
                             OrderInfoName=a.OrderInfoName,
                              OrderInfoSalePrice=a.OrderInfoSalePrice,
                               OrderInfoState= (int)a.OrderInfoState,
                               OrderInfoWaybillNum=a.OrderInfoWaybillNum,
                                OrderName=c.CommodityName,
                                 SmallImage=c.CommodityImage,
                                  OrderWheShipments=a.OrderWheShipments
                     }).ToList();

            for (int i = s.Count(); i > 0; i--)
            {
               int g = 0;
                for (int j= s.Count(); j > 0; j--)
                {
                    if(s[i-1].Id==s[j-1].Id)
                    {
                        g++;
                        if(g==2)
                        {
                            s.Remove(s[i-1]);
                            break;
                        }
                    }
                }
            }
            if(cid!=0)
            {
                s = s.Where(s => s.OrderInfoState == cid).ToList();
            }
            return s;
        }


        public async Task<CommodSpecifica> AddCoPAsync(CreateUpdateCommodSpecificaDto comp)
        {
            var vgbjvj = DateTime.Now;
            string[] result = comp.CommodSpeciOrder.Split(",");
            string k = "";
            for (int i = result.Length-comp.CommodSpeciDisplay; i < result.Length; i++)
            {
                if(i==result.Length-comp.CommodSpeciDisplay)
                {
                    k +=result[i];
                }else
                {
                       k +=","+result[i];
                }
            };
              comp.CommodSpeciOrder = k;
          var s=await _repository2.InsertAsync(ObjectMapper.Map<CreateUpdateCommodSpecificaDto,CommodSpecifica>(comp));
            return s;
        }

        public string GetEx()
        {
            KdApiSubscribeDemo kb = new KdApiSubscribeDemo();
            return kb.orderOnlineByJson();
        }

        public int SkuAdd(SkuUp skuup)
        {
            
            string Mname = "";
            for (int i = 0; i < skuup.SkuUp1.Length; i++)
            {
                if(i==0)
                {
                    Mname += skuup.SkuUp1[i].name;
                }else
                {
                    Mname +=","+skuup.SkuUp1[i].name;
                }
            }
            _repository5.DeleteManyAsync(_repository5.Where(s => s.CommodId == skuup.commodid));
            for (int i = 0; i <skuup.SkuUp2.Length ; i++)
            {
                
                _repository5.InsertAsync(new SpecificaPars { CommodId=skuup.commodid,SpecificaName=Mname,orderSpId="", SpName=skuup.SkuUp2[i].sku, SpecificaPrice= skuup.SkuUp2[i].price,Proid=Convert.ToInt32(skuup.SkuUp2[i].stock) });
            }
            
            return 1;
        }
        [HttpGet]
        public List<Attributes> GetSku(string lan)
        {
      List<SpecificaPars> spe=_repository5.Where(s=>s.CommodId==lan).ToList();
            if(spe.Count()==0)
            {
                return null;
            }
           string[] mna= spe[0].SpecificaName.Split(",");
      List<Attributes> attrar=new List<Attributes>();
            for (int i = 0; i < mna.Length; i++)
            {
                var s =new Attributes();
                s.name = mna[i];
                string bn="";
                for (int j = 0; j < spe.Count(); j++)
                {
                   var ml= spe[j].SpName.Split(";");
                    if(!bn.Contains(ml[i]))
                    {
                        if(bn=="")
                        {
                            bn += ml[i];
                        }else
                        {
                            bn+=","+ml[i];
                        }
                    }

                }
                s.item = bn.Split(",");

                attrar.AddLast(s);
            }

            return attrar;
        }
        [HttpPost]
        public SkuUp GetSkuUp(string sk)
        {
            SkuUp sku = new SkuUp();
            List<SpecificaPars> spe = _repository5.Where(s => s.CommodId == sk).ToList();
            if (spe.Count()<1)
            {
                return sku;
            }

            string[] mna = spe[0].SpecificaName.Split(",");
            List<Attributes> attrar = new List<Attributes>();
            for (int i = 0; i < mna.Length; i++)
            {
                var s = new Attributes();
                s.name = mna[i];
                string bn = "";
                for (int j = 0; j < spe.Count(); j++)
                {
                    var ml = spe[j].SpName.Split(";");
                    if (!bn.Contains(ml[i]))
                    {
                        if (bn == "")
                        {
                            bn += ml[i];
                        }
                        else
                        {
                            bn += "," + ml[i];
                        }
                    }

                }
                s.item = bn.Split(",");

                attrar.AddLast(s);
            }
            sku.SkuUp1 = attrar.ToArray();
            List<Sku> skuar1 = new List<Sku>();
            for (int f = 0; f < spe.Count(); f++)
            {
                Sku skusm = new Sku();
                skusm.price = spe[f].SpecificaPrice;
                skusm.sku = spe[f].SpName;
                skusm.stock = spe[f].Proid.ToString();
                skuar1.AddLast(skusm);
            }
            sku.SkuUp2 = skuar1.ToArray();
            return sku;
        }


        

        //public string UserPost(CreateUpdateFreeActionDto input)
        //{

        //    var res = _repository.InsertAsync(ObjectMapper.Map<CreateUpdateFreeActionDto, FreeActions>(input));

        //    return "成功";

        //}


    }


  }

